package com.wxzz.elearning.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloud.apigateway.sdk.utils.Client;
import com.cloud.apigateway.sdk.utils.Request;
import com.huawei.common.obs.ObsConfig;
import com.huawei.vod.client.VodClient;
import com.huawei.vod.client.VodConfig;
import com.huawei.vod.model.Review;
import com.huawei.vod.model.Thumbnail;
import com.huawei.vod.model.asset.CreateAssetByFileReq;
import com.huawei.vod.model.asset.SubtitleReq;
import com.wxzz.elearning.common.constants.LiveConstants;
import com.wxzz.elearning.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 华为云调用sdk
 *
 * @author zhangjunjie
 * @date 2021.4.15
 */
@Slf4j
public class HuaweiLiveUtil {

    public static void main(String[] args) {
        String date = LocalDate.now().minusDays(30).toString() + "T00:00:00Z";
        String get = HuaweiLiveUtil.sendRequest("GET", "https://live.cn-north-4.myhuaweicloud.com/v2/" + LiveConstants.PROJECT_ID + "/stats/traffic/summary" +
                "?play_domains=wxzzplay.mixchains.com&stream=6c1e8d7a-5216-4191-9c09-86a9c4625c8b&start_time=" + date, null);
        JSONObject jsonObject = JSONObject.parseObject(get);
        JSONArray traffic_list = jsonObject.getJSONArray("traffic_list");
        JSONObject object = (JSONObject) traffic_list.get(0);
        Long value = object.getLong("value");
        System.err.println(value / 1024);
    }

    /**
     * 获取消耗流量
     *
     * @param stream
     * @return
     */
    public static Long getConsumptionFlow(String stream) {
        try {
            String date = LocalDate.now().minusDays(30).toString() + "T00:00:00Z";
            String get = HuaweiLiveUtil.sendRequest("GET", "https://live.cn-north-4.myhuaweicloud.com/v2/" + LiveConstants.PROJECT_ID + "/stats/traffic/summary" +
                    "?play_domains=wxzzplay.mixchains.com&stream=" + stream + "&start_time=" + date, null);
            JSONObject jsonObject = JSONObject.parseObject(get);
            JSONArray traffic_list = jsonObject.getJSONArray("traffic_list");
            JSONObject object = (JSONObject) traffic_list.get(0);
            Long value = object.getLong("value");
            return value / 1024;
        } catch (Exception e) {
            log.info("华为云获取直播拉流流量异常:{}", e.getMessage());
            return 0L;
        }
    }

    public static String sendRequest(String requestMethod, String url, String jsonBody) {
        Request request = new Request();
        try {
            //Set the AK/SK to sign and authenticate the request.
            request.setKey(LiveConstants.AK);
            request.setSecret(LiveConstants.SK);
            //The following example shows how to set the request URL and parameters to query a VPC list.
            //Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH.
            request.setMethod(requestMethod);
            //Set a request URL in the format of https://{Endpoint}/{URI}.
            request.setUrl(url);
            //Set parameters for the request URL.
            request.addQueryStringParam("limit", "2");
            //Add header parameters, for example, X-Domain-Id for invoking a global service and X-Project-Id for invoking a project-level service.
            request.addHeader("X-Project-Id", LiveConstants.PROJECT_ID);
            request.addHeader("Content-Type", "application/json");
            //Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped.
            request.setBody(jsonBody);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("请求华为云api异常:" + e.getMessage());
        }
        CloseableHttpClient client = null;
        try {
            HttpRequestBase signedRequest = Client.sign(request);
            client = HttpClients.custom().build();
            HttpResponse response = client.execute(signedRequest);
            System.out.println(response.getStatusLine().toString());
            Header[] resHeaders = response.getAllHeaders();
            for (Header h : resHeaders) {
                System.out.println(h.getName() + ":" + h.getValue());
            }
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // System.out.println(System.getProperty("line.separator") + EntityUtils.toString(resEntity, "UTF-8"));
                return EntityUtils.toString(resEntity, "UTF-8");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("请求华为云api异常:" + e.getMessage());
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String sendRequestFile(String url, String jsonBody) {
        Request request = new Request();
        try {
            //Set the AK/SK to sign and authenticate the request.
            //The following example shows how to set the request URL and parameters to query a VPC list.
            //Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH.
            request.setMethod("PUT");
            //Set a request URL in the format of https://{Endpoint}/{URI}.
            request.setUrl(url);
            //Set parameters for the request URL.
            request.addQueryStringParam("limit", "2");
            //Add header parameters, for example, X-Domain-Id for invoking a global service and X-Project-Id for invoking a project-level service.
            request.addHeader("X-Project-Id", LiveConstants.PROJECT_ID);
            request.addHeader("Content-Type", "video/mp4");
            //Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped.
            request.setBody(jsonBody);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("请求华为云api异常:" + e.getMessage());
        }
        CloseableHttpClient client = null;
        try {
            HttpRequestBase signedRequest = Client.sign(request);
            client = HttpClients.custom().build();
            HttpResponse response = client.execute(signedRequest);
            System.out.println(response.getStatusLine().toString());
            Header[] resHeaders = response.getAllHeaders();
            for (Header h : resHeaders) {
                System.out.println(h.getName() + ":" + h.getValue());
            }
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // System.out.println(System.getProperty("line.separator") + EntityUtils.toString(resEntity, "UTF-8"));
                return EntityUtils.toString(resEntity, "UTF-8");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("请求华为云api异常:" + e.getMessage());
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static VodClient initVodClient() {
        return new VodClient(initVodConfig(), initObsConfig());
    }

    //VodConfig初始化配置
    public static VodConfig initVodConfig() {
        VodConfig vodConfig = new VodConfig();
        //设置项目ID，参考前提条件获取。
        vodConfig.setProjectId(LiveConstants.PROJECT_ID);
        //设置点播服务节点地址，参考前提条件获取
        vodConfig.setEndPoint("vod.cn-north-4.myhuaweicloud.com");
        //设置ak，参考前提条件获取
        vodConfig.setAk(LiveConstants.AK);
        //设置sk，参考前提条件获取
        vodConfig.setSk(LiveConstants.SK);
        //若使用临时ak/sk，必须设置SecurityToken，参考前提条件获取
        //vodConfig.setSecurityToken("securityToken");
        //设置IAM服务节点地址，参考前提条件获取，需要和点播服务节点地址在同一个区域(region)。在使用临时ak，sk场景下必须配置。
        vodConfig.setIamEndPoint("iam.cn-north-4.myhuaweicloud.com");
        return vodConfig;
    }

    //ObsConfig上传配置
    public static ObsConfig initObsConfig() {
        //因点播服务使用了对象存储服务（OBS）进行文件存储，因此文件的上传均需要和对象存储服务进行交互，所以此处需要配置OBS的EndPoint
        ObsConfig obsConfig = new ObsConfig();
        //设置OBS服务节点地址
        obsConfig.setEndPoint("obs.cn-north-4.myhuaweicloud.com");
        obsConfig.setPartSize(20); //设置上传视频时分段上传时切分的每一段大小，最小为5M，最大不能超过20M
        obsConfig.setConcurrencyLevel(0);//设置上传时的并发数，若设置为0则表示串行上传
        return obsConfig;
    }

    //请求媒资创建并上传
    public static CreateAssetByFileReq buildCreateAssetReq() {
        CreateAssetByFileReq req = new CreateAssetByFileReq();
        //设置媒资标题,长度不超过128个字节，utf-8编码
        req.setTitle("title");
        //设置视频描述, 长度不超过1024个字节
        req.setDescription("description");
        //设置媒资分类id
        //req.setCategoryId(1);
        //设置媒资文件的本地存储地址，如d://test.mp4，若上传的是HLS格式，则需要设置为存储m3u8文件的文件夹，如E://tmp/transcode/out
        //req.setVideoFileUrl("C:\\Users\\zhangjunjie\\Videos\\Captures\\League of Legends (TM) Client 2020-10-31 11-34-57.mp4");
        //设置封面的本地存储地址，如d://cover.png，如果需要上传封面，则该参数必填
        // req.setCoverFileUrl( "coverAddress");
        //设置字幕文件的本地存储地址，如d://subtitle.srt，如果需要上传字幕，则该参数必填
        //req.setSubtitleFileUrl("C:\\Users\\zhangjunjie\\Videos\\Captures\\League of Legends (TM) Client 2020-10-31 11-34-57.mp4");
        //设置视频文件名，可以带后缀，也可以不带后缀
        req.setVideoName("videoName");
        //设置上传文件类型，其中，上传文件的格式必须设置为大写。支持上传视频文件格式：MP4、TS、MOV、MXF、MPG、FLV、WMV、AVI、M4V、F4V、MPEG、3GP、ASF、MKV、HLS，支持上传音频文件格式：MP3、OGG、WAV、WMA、APE、FLAC、AAC、AC3、MMF、AMR、M4A、M4R、WV、MP2，若上传格式为音频文件，则不支持转码、添加水印和添加字幕。
        req.setVideoType("MP4");
        //设置封面图片文件类型，当前支持JPG、PNG，如果不上传封面，则该参数不用填写。
        //req.setCoverType("PNG");
        //设置字幕参数
        List<SubtitleReq> subtitleReqs = new ArrayList<>();
        SubtitleReq subtitleReq = new SubtitleReq();
        //字幕id，目前只支持上传一个字幕文件，取值为[1,8]
        subtitleReq.setId(1);
        //字幕文件类型，目前只支持SRT文件
        subtitleReq.setType("SRT");
        //字幕语言类型，目前只能设置为“CN”和“EN”
        subtitleReq.setLanguage("CN");
        //字幕文件MD5值
        subtitleReq.setMd5("EIq3IMk3Cx8Dh6ga/peS/Q==");
        subtitleReqs.add(subtitleReq);
        req.setSubtitles(subtitleReqs);
        //是否自动发布，取值[0，1]，0表示不自动发布，1表示自动发布；缺省值为0
        req.setAutoPublish(1);
        //是否自动预热到CDN，取值[0，1]
        req.setAutoPreheat(1);
        //设置媒资转码的模板组的Name，具体的模板组可以在点播控制台进行创建和查看
        //req.setTemplateGroupName("templateGroupName");
        //设置截图参数
        Thumbnail thumbnail = new Thumbnail();
        //设置截图类型为固定时间间隔采样截图，TIME为定时采样，DOTS为指定时间点截图。
        thumbnail.setType(Thumbnail.TypeEnum.TIME);
        //设定时间间隔（取值为[1,100]区间的整数）；type设置为DOTS时需设置dots数组指定截图时间点。
        thumbnail.setTime(10);
        //指定第1张截图结果作为封面
        thumbnail.setCoverPosition(1);
        req.setThumbnail(thumbnail);
        //设置审核参数，目前“华东-上海二”区域的点播服务暂不支持此功能。
        Review review = new Review();
        // 设置截图时间间隔，单位秒（取值为5或者10）
        review.setInterval(5);
        // 设置政治人物检测时的置信度（取值为[-1,100]之间的整数，取值-1表示为默认值53）
        review.setPolitics(80);
        // 设置暴恐元素检测时的置信度（取值为[-1,100]之间的整数，取值-1表示为默认值80）
        review.setTerrorism(80);
        // 设置涉黄内容检测时的置信度（取值为[-1,100]之间的整数，取值-1表示为默认值80）
        review.setPorn(80);
        req.setReview(review);
        // 设置是否自动加密
        req.setAutoEncrypt(1);
        return req;
    }
}
